﻿/**
 * ...
 * @author alijaya
 */

package homponex.core;
import homponex.utils.DynamicUtils;

class Button extends Component
{

	public var phase(default, null):ButtonPhase;
	
	#if flash9
	private var skinUp:S9G;
	private var skinOver:S9G;
	private var skinDown:S9G;
	private var skinDisabled:S9G;
	
	private var curSkin:S9G;
	#end
	
	public function new() 
	{
		super();
		
		setStyle(Style.defaultStyle.getStyle(DynamicUtils.getClassTree(Type.getClass(this))));
	}
	
	public override function setStyle(s:Dynamic)
	{
		super.setStyle(s);
		
		#if flash9
		skinUp = cast(DynamicUtils.notNull(style.up, Style.skinWhite).clone());
		skinOver = cast(DynamicUtils.notNull(style.over, Style.skinWhite).clone());
		skinDown = cast(DynamicUtils.notNull(style.down, Style.skinWhite).clone());
		skinDisabled = cast(DynamicUtils.notNull(style.disabled, Style.skinWhite).clone());
		
		changePhase(ButtonPhase.UP);
		#end
	}
	
	private function changePhase(phase:ButtonPhase)
	{
		this.phase = phase;
		update_phase();
	}
	
	
	
	/////////////////////
	// Update Function //
	/////////////////////
	
	private function update_phase()
	{
		#if flash9
		if (curSkin != null) view.removeChild(curSkin.view);
		#end
		switch(phase)
		{
			case ButtonPhase.UP:
			
			#if flash9
			curSkin = skinUp;
			#end
			
			case ButtonPhase.OVER:
			
			#if flash9
			curSkin = skinOver;
			#end
			
			case ButtonPhase.DOWN:
			
			#if flash9
			curSkin = skinDown;
			#end
			
			case ButtonPhase.DISABLED:
			
			#if flash9
			curSkin = skinDisabled;
			#end
			
		}
		
		#if flash9
		view.addChild(curSkin.view);
		update_width();
		update_height();
		#end
	}
	
	private override function update_curEnabled()
	{
		if (curEnabled)
		{
			changePhase(ButtonPhase.UP);
		} else
		{
			changePhase(ButtonPhase.DISABLED);
		}
	}
	
	private override function update_width()
	{
		curSkin.width = width;
	}
	
	private override function update_height()
	{
		curSkin.height = height;
	}
	
	
	
	private override function update_click()
	{
		changePhase(ButtonPhase.OVER);
	}
	
	private override function update_release()
	{
		changePhase(ButtonPhase.UP);
	}
	
	private override function update_over()
	{
		changePhase(ButtonPhase.OVER);
	}
	
	private override function update_out()
	{
		changePhase(ButtonPhase.UP);
	}
	
	private override function update_down()
	{
		changePhase(ButtonPhase.DOWN);
	}
	
}

enum ButtonPhase
{
	UP;
	OVER;
	DOWN;
	DISABLED;
}